<!-- 律师费用 -->
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 客户树 -->
      <el-col :lg="4" :xs="24" class="mb-[12px]">
        <business-tree v-model="queryParams.busId" @node-click="handleQuery" />
      </el-col>
      <!-- 律师费用列表 -->
      <el-col :lg="20" :xs="24">
        <!-- <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="关键字" prop="clientName">
              <el-input
                v-model="queryParams.clientName"
                placeholder="客户名称"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleQuery">
                <i-ep-search />
                搜索
              </el-button>
              <el-button @click="handleResetQuery">
                <i-ep-refresh />
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div> -->

        <el-card shadow="never" class="table-container">
          <template #header>
            <div class="flex-x-between">
              <div>
                <el-button type="success" @click="handleOpenDialog()">
                  <i-ep-plus />
                  编辑
                </el-button>
              </div>
            </div>
          </template>

          <el-table
            v-loading="loading"
            :data="pageData"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              label="业务类型"
              align="center"
              prop="businessName"
              width="130"
            />
            <el-table-column
              label="分段基数金额"
              align="center"
              prop="cardinalityAmount"
              width="150"
            />
            <el-table-column
              label="起始金额"
              align="center"
              prop="startPrice"
              width="130"
            />
            <el-table-column
              label="结束金额"
              align="center"
              width="130"
              prop="endPrice"
            />
            <el-table-column
              label="最低收费金额
"
              align="center"
              width="130"
              prop="minPrice"
            />
            <el-table-column
              label="最高收费金额
"
              align="center"
              width="130"
              prop="maxPrice"
            />
            <el-table-column label="计算方式" align="center" width="130">
              <template #default="scope">
                <div v-if="scope.row.percentFlag == 'PERCENT'">按比例</div>
                <div v-else>固定的金额</div>
              </template>
            </el-table-column>
            <el-table-column
              label="最低收比例"
              align="center"
              prop="minPercent"
              width="120"
            />
            <el-table-column
              label="最高收比例"
              align="center"
              prop="maxPercent"
              width="120"
            />
            <el-table-column
              label="最低收固定金额"
              align="center"
              prop="minFixedAmount"
              width="150"
            />
            <el-table-column
              label="最高收固定金额"
              align="center"
              prop="maxFixedAmount"
              width="150"
            />
            <el-table-column fixed="right" label="操作" width="120">
              <template #default="scope">
                <el-button
                  type="danger"
                  size="small"
                  link
                  @click="handleDelete(scope.row.id)"
                >
                  <i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.current"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 律师费用表单弹窗 -->
    <el-drawer
      v-model="dialog.visible"
      :title="dialog.title"
      size="90%"
      @close="handleCloseDialog"
    >
      <el-table
        :data="lawyerFeeData"
        :border="true"
        style="width: 100%"
        max-height="250"
      >
        <el-table-column prop="newBus" label="业务分类" width="140">
          <template #default="scope">
            <el-select
              v-if="scope.row.isEdit"
              v-model="scope.row.newBus"
              placeholder="请选择"
              value-key="id"
              @change="businessSelectChange(scope.row)"
            >
              <el-option
                v-for="item in scope.row.busList"
                :key="item.id"
                :label="item.categoryName"
                :value="item"
              />
            </el-select>
            <span v-else>
              {{ scope.row.businessName }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="cardinalityAmount"
          label="分段基数金额"
          width="140"
        >
          <template #default="scope">
            <el-input
              v-if="scope.row.isEdit"
              v-model="scope.row.cardinalityAmount"
              placeholder="分段基数金额"
            />
            <span v-else>
              {{ scope.row.cardinalityAmount }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="startPrice" label="起始金额" width="140">
          <template #default="scope">
            <el-input
              v-if="scope.row.isEdit"
              v-model="scope.row.startPrice"
              placeholder="起始金额"
            />
            <span v-else>
              {{ scope.row.startPrice }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="endPrice" label="结束金额" width="140">
          <template #default="scope">
            <el-input
              v-if="scope.row.isEdit"
              v-model="scope.row.endPrice"
              placeholder="结束金额"
            />
            <span v-else>
              {{ scope.row.endPrice }}
            </span>
          </template>
        </el-table-column>

        <el-table-column prop="minPrice" label="最低收费金额" width="140">
          <template #default="scope">
            <el-input
              v-if="scope.row.isEdit"
              v-model="scope.row.minPrice"
              placeholder="最低收费金额"
            />
            <span v-else>
              {{ scope.row.minPrice }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="maxPrice" label="最高收费金额" width="140">
          <template #default="scope">
            <el-input
              v-if="scope.row.isEdit"
              v-model="scope.row.maxPrice"
              placeholder="最高收费金额"
            />
            <span v-else>
              {{ scope.row.maxPrice }}
            </span>
          </template>
        </el-table-column>

        <el-table-column prop="percentFlag" label="计算方式" width="140">
          <template #default="scope">
            <el-radio-group
              v-if="scope.row.isEdit"
              v-model="scope.row.percentFlag"
            >
              <el-radio value="PERCENT">按比例</el-radio>
              <el-radio value="FIXED">固定的金额</el-radio>
            </el-radio-group>
            <span v-else>
              <div v-show="scope.row.percentFlag == 'PERCENT'">按比例</div>
              <div v-show="scope.row.percentFlag == 'FIXED'">固定的金额</div>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="minPercent" label="最低收比例" width="140">
          <template #default="scope">
            <el-input
              v-if="scope.row.isEdit && scope.row.percentFlag == 'PERCENT'"
              v-model="scope.row.minPercent"
              placeholder="最低收比例"
            />
            <span v-else>
              {{ scope.row.minPercent }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="maxPercent" label="最高收比例" width="140">
          <template #default="scope">
            <el-input
              v-if="scope.row.isEdit && scope.row.percentFlag == 'PERCENT'"
              v-model="scope.row.maxPercent"
              placeholder="最高收比例"
            />
            <span v-else>
              {{ scope.row.maxPercent }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="minFixedAmount"
          label="最低收固定金额"
          width="160"
        >
          <template #default="scope">
            <el-input
              v-if="scope.row.isEdit && scope.row.percentFlag == 'FIXED'"
              v-model="scope.row.minFixedAmount"
              placeholder="最低收固定金额"
            />
            <span v-else>
              {{ scope.row.minFixedAmount }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="maxFixedAmount"
          label="最高收固定金额"
          width="160"
        >
          <template #default="scope">
            <el-input
              v-if="scope.row.isEdit && scope.row.percentFlag == 'FIXED'"
              v-model="scope.row.maxFixedAmount"
              placeholder="最高收固定金额"
            />
            <span v-else>
              {{ scope.row.maxFixedAmount }}
            </span>
          </template>
        </el-table-column>

        <el-table-column prop="right" label="操作" min-width="100">
          <template #default="scope">
            <el-button
              v-if="!scope.row.isEdit"
              link
              type="primary"
              size="small"
              @click.prevent="stateChange(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              v-else
              link
              type="primary"
              size="small"
              @click.prevent="stateChange(scope.row)"
            >
              保存
            </el-button>
            <el-button
              link
              type="danger"
              size="small"
              @click.prevent="deleteRow(scope.$index)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="display: flex; align-items: center; justify-content: center">
        <el-button
          class="mt-4"
          style="width: 10%"
          type="primary"
          @click="onAddItem"
        >
          添加
        </el-button>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Job",
  inheritAttrs: false,
});

import lawyerfeeAPI, { LawyerFeeForm, LawyerFeeVO } from "@/api/lawyerfee";
import bussinessAPI from "@/api/business";

const queryFormRef = ref(ElForm);
const userFormRef = ref(ElForm);

const loading = ref(false);
const removeIds = ref([]);
const total = ref(0);
const pageData = ref<LawyerFeeVO[]>();
/** 律师费用查询参数  */
const queryParams = reactive({
  current: 1,
  pageSize: 10,
  busId: undefined,
});

/**  律师费用弹窗对象  */
const dialog = reactive({
  visible: false,
  title: "",
});

// 律师费用表单数据
const formData = reactive<LawyerFeeForm>({
  id: undefined,
  isEdit: true,
  busList: [],
  newBus: "",
  businessId: undefined,
  businessName: "",
  startPrice: undefined,
  endPrice: undefined,
  percentFlag: "",
  minPercent: undefined,
  maxPercent: undefined,
  minFixedAmount: undefined,
  maxFixedAmount: undefined,
  cardinalityAmount: undefined,
  minPrice: "",
  maxPrice: "",
});

const lawyerFeeData = ref<any>([]);
/** 编辑状态转换 */
const stateChange = (item: any) => {
  item.isEdit = !item.isEdit;
};
/** 删除一条数据 */
const deleteRow = (index: number) => {
  lawyerFeeData.value.splice(index, 1);
};
/** 添加一条数据 */
const onAddItem = () => {
  lawyerFeeData.value.push({ ...formData });
};

/** 律师费用表单校验规则  */
const rules = reactive({
  clientName: [
    { required: true, message: "客户名称不能为空", trigger: "blur" },
  ],
  businessName: [{ required: true, message: "地址不能为空", trigger: "blur" }],
  lawFirmId: [{ required: true, message: "律所不能为空", trigger: "blur" }],
  lawyerId: [{ required: true, message: "律师不能为空", trigger: "blur" }],
  clientPhone: [
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  lawyerfeeAPI
    .getLawyerFee(Number(queryParams.busId))
    .then((data) => {
      console.log(data, "律师费用列表");
      pageData.value = data;
      total.value = data.length;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function handleResetQuery() {
  // queryFormRef.value.resetFields();
  queryParams.current = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/**
 * 打开弹窗
 *
 * @param id 律师费用ID
 */
async function handleOpenDialog(val?: any) {
  dialog.visible = true;
  formData.busList = await bussinessAPI.getBussiness();
  Object.assign(lawyerFeeData.value, { ...pageData.value });
  dialog.title = "编辑律师费用";
}
/** 选中业务时触发 */
const businessSelectChange = (item: any) => {
  item.businessId = item.newBus.id;
  item.businessName = item.newBus.categoryName;
};

/** 关闭弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  lawyerFeeData.value = [];
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  console.log(formData, "表单提交时的form");
  loading.value = true;
  lawyerfeeAPI
    .updateLawyerFee(lawyerFeeData.value)
    .then(() => {
      ElMessage.success("修改律师费用成功");
      handleCloseDialog();
      handleResetQuery();
    })
    .finally(() => (loading.value = false));
  // userFormRef.value.validate((valid: any) => {
  //   if (valid) {
  //     const userId = formData.id;
  //     loading.value = true;
  //     lawyerfeeAPI
  //       .updateLawyerFee(lawyerFeeData.value)
  //       .then(() => {
  //         if (userId) {
  //           ElMessage.success("修改律师费用成功");
  //         } else {
  //           ElMessage.success("新增律师费用成功");
  //         }
  //         handleCloseDialog();
  //         handleResetQuery();
  //       })
  //       .finally(() => (loading.value = false));
  //   }
  // });
}, 3000);

/** 删除律师费用 */
function handleDelete(id?: number) {
  const userIds = [id || removeIds.value].join(",");
  console.log(id);
  ElMessageBox.confirm("确认删除律师费用?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      lawyerfeeAPI
        .deleteLawyerFee(userIds)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  // handleQuery();
});
</script>
